// StartupInitializer.java
package swb.api.com.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import swb.api.com.repository.SysUserRepository;
import swb.api.com.repository.SysUserRoleRepository;
import swb.api.com.repository.dto.SysUser;
import swb.api.com.repository.dto.SysUserRole;

import java.time.LocalDateTime;

@Component
public class StartupInitializer implements CommandLineRunner {

    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysUserRoleRepository sysUserRoleRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) throws Exception {
        // 检查是否存在管理员账户，如果没有则创建默认管理员
        if (sysUserRepository.findByUsername("admin") == null) {
            createDefaultAdmin();
        }
    }

    private void createDefaultAdmin() {
        // 创建默认管理员账户
        SysUser admin = new SysUser();
        admin.setUsername("admin");
        admin.setPassword(passwordEncoder.encode("admin123")); // 默认密码
        admin.setNickname("系统管理员");
        admin.setStatus(1);
        admin.setCreateTime(LocalDateTime.now());
        admin.setUpdateTime(LocalDateTime.now());

        admin = sysUserRepository.save(admin);

        // 分配管理员角色
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(admin.getId());
        userRole.setRoleId(1L); // 管理员角色ID
        sysUserRoleRepository.save(userRole);

        System.out.println("默认管理员账户已创建，用户名: admin, 密码: admin123");
    }
}
